package service

import (
	"errors"
	"fitness/go-admin/internal/model"
	"fitness/go-admin/internal/repository"
	"time"

	"gorm.io/gorm"
)

type OperationLogService interface {
	CreateLog(log *model.OperationLog) error
	GetLogList(req *model.OperationLogListReq) ([]*model.OperationLogListItem, int64, error)
	GetLogDetail(id uint) (*model.OperationLogDetailResp, error)
	DeleteLog(id uint) error
	DeleteBatchLogs(ids []uint) error
}

type operationLogService struct {
	logRepo repository.OperationLogRepository
}

func NewOperationLogService(logRepo repository.OperationLogRepository) OperationLogService {
	return &operationLogService{
		logRepo: logRepo,
	}
}

// CreateLog 创建操作日志
func (s *operationLogService) CreateLog(log *model.OperationLog) error {
	// 参数验证
	if log.Username == "" {
		return errors.New("用户名不能为空")
	}
	if log.Path == "" {
		return errors.New("请求路径不能为空")
	}
	if log.Action == "" {
		return errors.New("操作类型不能为空")
	}
	if log.Resource == "" {
		return errors.New("资源类型不能为空")
	}

	// 设置创建时间
	log.CreatedAt = time.Now()

	// 调用Repository层创建
	return s.logRepo.Create(log)
}

// GetLogList 获取操作日志列表
func (s *operationLogService) GetLogList(req *model.OperationLogListReq) ([]*model.OperationLogListItem, int64, error) {
	// 参数验证
	if req.Page < 1 {
		req.Page = 1
	}
	if req.PageSize < 1 || req.PageSize > 100 {
		req.PageSize = 10
	}

	// 日期格式验证
	if req.StartDate != "" {
		if _, err := time.Parse("2006-01-02", req.StartDate); err != nil {
			return nil, 0, errors.New("开始日期格式错误，应为YYYY-MM-DD")
		}
	}
	if req.EndDate != "" {
		if _, err := time.Parse("2006-01-02", req.EndDate); err != nil {
			return nil, 0, errors.New("结束日期格式错误，应为YYYY-MM-DD")
		}
	}

	// 调用Repository层查询
	logs, total, err := s.logRepo.List(req)
	if err != nil {
		return nil, 0, err
	}

	return logs, total, nil
}

// GetLogDetail 获取操作日志详情
func (s *operationLogService) GetLogDetail(id uint) (*model.OperationLogDetailResp, error) {
	// 参数验证
	if id == 0 {
		return nil, errors.New("日志ID不能为空")
	}

	// 调用Repository层查询
	detail, err := s.logRepo.GetDetailByID(id)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, errors.New("操作日志不存在")
		}
		return nil, err
	}

	return detail, nil
}

// DeleteLog 删除操作日志
func (s *operationLogService) DeleteLog(id uint) error {
	// 参数验证
	if id == 0 {
		return errors.New("日志ID不能为空")
	}

	// 检查日志是否存在
	_, err := s.logRepo.GetByID(id)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return errors.New("操作日志不存在")
		}
		return err
	}

	// 调用Repository层删除
	return s.logRepo.Delete(id)
}

// DeleteBatchLogs 批量删除操作日志
func (s *operationLogService) DeleteBatchLogs(ids []uint) error {
	// 参数验证
	if len(ids) == 0 {
		return errors.New("日志ID列表不能为空")
	}

	// 限制批量删除数量
	if len(ids) > 100 {
		return errors.New("单次批量删除不能超过100条记录")
	}

	// 调用Repository层删除
	return s.logRepo.DeleteBatch(ids)
}
